package com.jinxin.platform.cdelecinspect.utils;

import com.jinxin.platform.cdelecinspect.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * Description: bccah
 * Created by 34759 on 2019/8/16 17:33
 */
@Slf4j
@Component
public class UploadFileUtil {
    private final static Logger logger = LoggerFactory.getLogger(UploadFileUtil.class);

    public static String uploadFile(MultipartFile file, String uploadPath, String resBasePath){
        try{
            if(file!=null){
                String fileName = file.getOriginalFilename();
                String ext = fileName.substring(fileName.lastIndexOf("."));
                String newfileName = Utils.getUuid() + ext;
                String fileSavePath = Constants.UPLOAD_FILE_MIDDLE_PATH + newfileName;
                String targetPath = uploadPath + fileSavePath;
                File targetFile = new File(targetPath);
                if(!targetFile.getParentFile().exists()){
                    targetFile.getParentFile().mkdirs();
                }
                targetFile.createNewFile();
                file.transferTo(targetFile);
                log.info("上传路径: " + fileSavePath);
                return resBasePath+fileSavePath;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static boolean deleteFile(String uploadPath, String filePath){
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
        String filepath = uploadPath + Constants.UPLOAD_FILE_MIDDLE_PATH + fileName;
        filepath = filepath.replace("\\", "/");
        // 删除附件文件
        File oldPic = new File(filepath);
        if (oldPic.exists()) {
            return oldPic.delete();
        }
        return false;
    }

}
